import datetime

from django.db import models
from datetime import datetime



class Menu(models.Model):
    name = models.CharField(max_length=30,verbose_name='标题')
    icon = models.CharField(max_length=30, verbose_name='图标')
    link = models.CharField(verbose_name='链接',max_length=100)
    seq = models.IntegerField(verbose_name='序号',default=0)
    parent= models.ForeignKey("Menu", verbose_name='父菜单',on_delete=models.PROTECT,null=True,blank=True)
    orderNumber = models.CharField(max_length=20,verbose_name='排序号', default="")
    class Meta:
        verbose_name = verbose_name_plural = '菜单'
        ordering = ['name']

    def __str__(self):
        return "%s"%self.name

    @staticmethod
    def  updateOrder():
        menus=Menu.objects.filter(parent__isnull=True).order_by('seq')
        c1=1
        for m in menus:
            if c1<10:
                m.orderNumber='0%s'%c1
            else:
                m.orderNumber='%s'%c1
            m.save()
            c1+=1

            c2=1
            for q in m.menu_set.all().order_by("seq"):
                if c2 < 10:
                    q.orderNumber = '%s#0%s' % (q.parent.orderNumber,c2)
                else:
                    q.orderNumber = '%s#%s' %  (q.parent.orderNumber,c2)
                q.save()
                c2+=1


    @staticmethod
    def getMenuString():
        menus=Menu.objects.filter(parent__isnull=True).order_by('orderNumber')
        r=""
        for m in menus:
            r+= "<li class='menu-list' onclick='c(%(id)s);'><a href=''   onclick='c(%(id)s);'><i class='%(icon)s'  onclick='c(%(id)s);'></i> <span>%(name)s</span></a>"%{'id':m.id,'icon':m.icon,'name':m.name};
            r+= "<ul class='sub-menu-list' id='%s'>"%m.id;
            for q in m.menu_set.all().order_by("seq"):
                r+= "<li><a href='%(link)s' onclick='c2(%(id)s);'  id='mc%(id)s'>&nbsp;&nbsp;&nbsp;&nbsp;%(name)s</a></li>"%{'link':q.link,'id':q.id,'name':q.name}
                r+= "</ul></li>"
        print(r)
        return r

